import { getDvaApp, RequestConfig } from 'umi';
import { createLogger } from 'redux-logger';
import { message } from 'antd';
// 引入viewerjs默认样式
import 'viewerjs/dist/viewer.css';
import React, { useReducer } from 'react';
import ThemeContext from '@/context/themeContext'


// 配置dva日志
export const dva = {
  config: {
    // onAction: createLogger(),
    onError(e: Error) {
      message.error(e.message, 3);
    },
  },
};



// 覆盖根组件
export function rootContainer(container: React.ReactNode) {

  return React.createElement(ThemeContext.Provider, {value: {
    color: '#fff'
  }}, container);
}

// umi的导航守卫
export function onRouteChange() {
  const dva = getDvaApp();
  let settingIndex = dva._models.findIndex((item: any)=>item.namespace === 'setting');
  let i18n = dva._models[settingIndex].state.i18n;
  if (!Object.keys(i18n).length) {
    dva._store.dispatch({
      type: 'setting/getSetting'
    })
  }
}

// 配置网络请求
let hasError = false;
const requestList: {method: string, url: string}[] = [];
// 
const baseURL = '//creationapi.shbwyz.com';
export const request: RequestConfig = {
  timeout: 10000,
  errorConfig: {},
  middlewares: [],
  requestInterceptors: [(url, options) => {
    // 把请求扔到requestLit里面
    let index = requestList.findIndex(item=>{
      if (item.method === options.method && item.url === url){
        return true
      }
      return false;
    })
    if (index !== -1){
      // 取消请求
      // throw new Error();
    }else{
      requestList.push({
        method: options.method as string,
        url
      })
    }
    url = url.indexOf('https')!==-1?url: `${baseURL+url}`;
    return {
      url,
      options: { ...options, interceptors: true },
    };
  }],
  responseInterceptors: [response => {
    // let values = response.headers.values();
    // for (let value of values) {
    //   console.log('value...', value);
    // }
    let index = requestList.findIndex(item=>{
      if (item.url === response.url){
        return true
      }
      return false;
    })
    if (index !== -1){
      requestList.splice(index, 1);
    }
    const codeMaps:{[key:number]:string} = {
      400: '客户端请求错误',
      403: '请求不被允许',
      404: '接口不存在',
      500: '服务器内部错误',
      502: '网关错误。',
      503: '服务不可用，服务器暂时过载或维护。',
      504: '网关超时。',
    };
    if (Object.keys(codeMaps).indexOf(String(response.status)) !== -1){
      if (!hasError){
        hasError = true;
        message.error({
          content: codeMaps[response.status],
          onClose: ()=>{
            hasError = false;
          }
        });
        return response.body;
      }
    }else{
      return response;
    }
    return {};
  }],
};

